use std::io::{stdin, stdout, Write};

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let mut client = TcpStream::connect("127.0.0.1:8888").await.unwrap();
    let (tx, mut rx) = mpsc::channel::<String>(1024);

    tokio::spawn(async move {
        let (mut reader, mut weiter) = client.split();
        loop {
            let mut buf = [0; 1024];
            let x = reader.read(&mut buf).await.unwrap();
            println!("{x}");
            if x == 0 {
                break;
            }
            stdout().write_all(&buf[..x]).unwrap();

            if let Some(msg) = rx.recv().await {
                weiter.write_all(msg.as_bytes()).await.unwrap()
            }
        }
    });

    loop {
        let mut buffer = String::new();
        stdin().read_line(&mut buffer).unwrap();
        tx.send(buffer.clone()).await.unwrap();
        buffer.clear();
    }
}
